﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BPM.Web;
using BPM.Service;
using BPM.ViewModel;
using BPM.Common;
using BPM.Entity;

namespace BPM.Controllers
{
    public class PurchaseOrderController : InternalViewController
    {
        #region CreatePurchaseOrder

        /// <summary>
        /// create purchase order and wait for review
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult CreatePurchaseOrder()
        {
            var vm = new CreatePurchaseOrderViewModel()
            {
                Barcode = new BarcodeService().RandomBarcodeNumber()
            };

            return CreatePurchaseOrderView(vm);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreatePurchaseOrder(CreatePurchaseOrderViewModel vm, FormCollection form)
        {
            //Read data from form, and check input errors.
            string error = null;
            for (int i = 1; i <= vm.MaterialNumbers; i++)
            {
                var materialId = ParsePositiveInt(form["MaterialId_" + i]);

                if (materialId > 0)
                {
                    var amount = ParsePositiveInt(form["Numbers_" + i]);
                    var payMode = form["PayMode_" + i];
                    var deliveryTime = form["DeliveryTime_" + i];

                    //如果数据大于0，表示此行记录的物料需要进货。否则，表示不需要购买此物料。
                    if (error == null)
                    {
                        DateTime time;
                        if (amount > 0 && !DateTime.TryParse(deliveryTime, out time)) error = "日期的格式不正确！";
                    }

                    vm.Materials.Add(new PurchaseMaterial()
                    {
                        MaterialId = materialId,
                        Amount = amount,
                        PaymentMode = payMode,
                        DeliveryTime = deliveryTime
                    });
                }
            }
            vm.MaterialNumbers = vm.Materials.Count;
            if (vm.Materials.All(m => m.Amount <= 0)) error = "所有物料的进货总量不能为0！";

            if (error != null)
            {
                this.ViewData["Error"] = error;
            }
            else
            {
                var res = CreatePurchaseOrderCore(vm, this.CurrentUser);
                if (res)
                {
                    return RedirectToAction(a => a.PurchaseOrder.MyPurchaseOrderList);
                }
                else
                {
                    this.ViewData["Error"] = res.Message;
                }
            }

            return CreatePurchaseOrderView(vm);
        }

        private ActionResult CreatePurchaseOrderView(CreatePurchaseOrderViewModel vm)
        {
            vm.Creator = this.CurrentUser.UserName;

            return View(vm);
        }

        private static Result CreatePurchaseOrderCore(CreatePurchaseOrderViewModel vm, User curUser)
        {
            Barcode barcode = null;
            var res = new BarcodeService().New(SysBarcodeCategories.PurchaseOrder, out barcode, vm.Barcode);
            if (!res) return res;

            var po = new PurchaseOrder();
            po.BarcodeId = barcode.Id;
            po.CreatorId = curUser.Id;
            po.CreatedTime = DateTime.Now;
            po.FinalInDeliveryTime = DateTime.Now;
            po.ItemList = new List<PurchaseOrderItem>();

            foreach (var material in vm.Materials)
            {
                //如果数据大于0，表示此行记录的物料需要进货。否则，表示不需要购买此物料。
                if (material.Amount > 0)
                {
                    po.ItemList.Add(new PurchaseOrderItem()
                    {
                        MaterialDefinitionId = material.MaterialId,
                        Amount = material.Amount,
                        DeliveryTime = DateTime.Parse(material.DeliveryTime),
                        PaymentMode = material.PaymentMode
                    });
                }
            }

            var poSvc = new PurchaseOrderService();
            return poSvc.Save(po);
        }

        #endregion

        /// <summary>
        /// Manager view pending purchase order list
        /// </summary>
        /// <returns></returns>
        public ActionResult PendingPurchaseOrderList(int? pageIndex)
        {
            var svc = new PurchaseOrderService();
            ViewData["list"] = svc.GetAll(pageIndex ?? 1, StaticData.PagingCount);
            return View();
        }

        /// <summary>
        /// Manager view a pending purchase order and apporve/deny this order
        /// </summary>
        /// <returns></returns>
        public ActionResult ViewPendingPurchaseOrder(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(AD.Singleton.PurchaseOrder.PendingPurchaseOrderList);
            }
            var svc = new PurchaseOrderService();
            var model = svc.GetById(id.Value);
            return View(model);
        }

        public ActionResult ApprovePendingPurchaseOrder(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(AD.Singleton.PurchaseOrder.PendingPurchaseOrderList);
            }

            var svc = new PurchaseOrderService();
			svc.Approve(id.Value);

            return RedirectToAction(AD.Singleton.PurchaseOrder.PendingPurchaseOrderList);
        }

        public ActionResult DeletePendingPurchaseOrder(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(AD.Singleton.PurchaseOrder.PendingPurchaseOrderList);
            }
			 
            var svc = new PurchaseOrderService();
            svc.Delete(id.Value);

            return RedirectToAction(AD.Singleton.PurchaseOrder.PendingPurchaseOrderList);
        }

        /// <summary>
        /// Buyer view pending purchase order list which only submitted by himself
        /// </summary>
        /// <returns></returns>
        public ActionResult MyPurchaseOrderList(int? page)
        {
            PurchaseOrderService service = new PurchaseOrderService();
            ViewData["list"] = service.GetAllByBuyer(page ?? 1, StaticData.PagingCount, CurrentUser);
            return View();
        }

        /// <summary>
        /// Buyer view a pending purchase order detailed information
        /// </summary>
        /// <returns></returns>
        public ActionResult MyPurchaseOrder(int id)
        {
            var model = new PurchaseOrderService().GetById(id);
            if (model != null)
            {
                return View(model);
            }
            else
            {
                return RedirectToAction(ad => ad.InternalDefaultView.Default);
            }
        }

        /// <summary>
        /// Storager view purchase order list
        /// </summary>
        /// <returns></returns>
        public ActionResult AllApprovedPurchaseOrderListByStorager(int? page)
        {
            var list = new PurchaseOrderService().GetApprovedOrders(page ?? 1, StaticData.PagingCount);
            this.ViewData["List"] = list;
            return View();
        }

        /// <summary>
        /// Storager view a purchase order
        /// </summary>
        /// <returns></returns>
        public ActionResult PurchaseOrderByStorager(int id)
        {
            var model = new PurchaseOrderService().GetById(id);
            if (model != null)
            {
                return View(model);
            }
            else
            {
                return RedirectToAction(ad => ad.InternalDefaultView.Default);
            }
        }
    }

    public class PurchaseOrderControllerActions : ControllerDefinition<PurchaseOrderController>
    {
        public readonly string CreatePurchaseOrder = "CreatePurchaseOrder";
        public readonly string PendingPurchaseOrderList = "PendingPurchaseOrderList";
        public readonly string ViewPendingPurchaseOrder = "ViewPendingPurchaseOrder";
        public readonly string ApprovePendingPurchaseOrder = "ApprovePendingPurchaseOrder";
        public readonly string DeletePendingPurchaseOrder = "DeletePendingPurchaseOrder";
        public readonly string MyPurchaseOrderList = "MyPurchaseOrderList";
        public readonly string MyPurchaseOrder = "MyPurchaseOrder";
        public readonly string AllApprovedPurchaseOrderListByStorager = "AllApprovedPurchaseOrderListByStorager";
        public readonly string PurchaseOrderByStorager = "PurchaseOrderByStorager";
    }
}